package com.ruyiadmin.springboot.common.components.core;

import com.alibaba.fastjson.JSON;
import com.ruyiadmin.springboot.common.beans.system.SystemConfig;
import com.ruyiadmin.springboot.common.core.business.enums.YesNo;
import com.ruyiadmin.springboot.domain.dto.system.SysUserDTO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 系统Session上下文类
 * </p>
 *
 * @author RuYiAdmin
 * @since 2022-07-20
 */
@Component
@EnableConfigurationProperties({SystemConfig.class})
@RequiredArgsConstructor
public class RuYiSessionContext {

    //region 系统Session私有属性

    private final RuYiRedisComponent redisUtils;
    private final SystemConfig systemConfig;
    private final RuYiTokenComponent tokenUtil;

    //endregion

    //region 获取当前用户信息

    /**
     * 获取当前用户信息
     *
     * @return 当前用户信息
     * @throws Exception 异常信息
     */
    public SysUserDTO getCurrentUserInfo() throws Exception {
        String token = tokenUtil.getToken();
        if (!StringUtils.isEmpty(token)) {
            Object value = redisUtils.get(token);
            return JSON.parseObject(value.toString(), SysUserDTO.class);
        }
        return null;
    }

    //endregion

    //region 获取当前用户机构编号

    /**
     * 获取当前用户机构编号
     *
     * @return 当前用户机构编号
     * @throws Exception 异常信息
     */
    public String getUserOrgId() throws Exception {
        String orgId = StringUtils.EMPTY;
        SysUserDTO user = getCurrentUserInfo();
        if (user != null) {
            if (user.getIsSupperAdmin() == YesNo.YES.ordinal()) {
                orgId = systemConfig.getOrgRoot();
            } else {
                orgId = user.getOrgId();
            }
        }
        return orgId;
    }

    //endregion

}
